#!/usr/bin/env bash

# Verify that all text files end in a trailing newline.

# Exit on first failure.
set -e

# Exit on unset variable.
set -u

# Change directory to repository root.
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
readonly SCRIPT_DIR
cd "${SCRIPT_DIR}/.."

success=0

while read -r line; do
  if ! [[ -s "${line}" && -z "$(tail -c 1 "${line}")" ]]; then
    printf "File must end in a trailing newline: %s\n" "${line}" >&2
    success=255
  fi
done < <(git ls-files \
  | xargs grep ".*" \
    --files-with-matches \
    --binary-files=without-match \
    --exclude="*third-party*")

exit "${success}"
